<template>
  <div class="userPage">
    <video src="/videos/background.mp4" muted autoplay loop class="bgVideo"></video>
    <section>
      <div class="form-box">
        <div class="form-value">
          <!-- 阻止表单默认提交行为 -->
          <form @submit.prevent="handleLogin">
            <!-- qiehuan -->
            <div class="navs" @click="toggleLoginType">
              <div v-if="ismain == false">切换主账号</div>
              <div v-if="ismain == true">切换子账号</div> <svg t="1757676887489" class="icon svg" viewBox="0 0 1024 1024"
                version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6907" width="20" height="20">
                <path
                  d="M886.2 604.8H137.8c-22.1 0-40 17.9-40 40 0 8.4 2.6 16.2 7 22.6 1.9 4.5 4.8 8.7 8.4 12.4L289.5 856c7.8 7.8 18 11.7 28.3 11.7s20.5-3.9 28.3-11.7c15.6-15.6 15.6-40.9 0-56.6L231.3 684.8h654.8c22.1 0 40-17.9 40-40s-17.8-40-39.9-40zM137.8 419.2h748.4c22.1 0 40-17.9 40-40 0-8.4-2.6-16.2-7-22.6-1.4-3.3-3.4-6.5-5.8-9.5L769.2 170.9c-14-17.1-39.2-19.6-56.3-5.6-17.1 14-19.6 39.2-5.6 56.3l96.3 117.6H137.8c-22.1 0-40 17.9-40 40s17.9 40 40 40z"
                  fill="#ffffff" p-id="6908"></path>
              </svg>
            </div>
            <h2>
              <img src="@/assets/images/logo.png" alt="" class="logo">
            </h2>


            <div v-if="ismain == true">
              <div class="inputbox">
                <i class="iconfont icon-user"></i>
                <input type="text" v-model="formData.username" required @input="validateForm('username')"
                  autocomplete="new-password">
                <label :class="{ 'active-label': formData.username }">用户名</label>
                <div v-if="errors.username" class="error">用户名不能为空</div>
              </div>
              <div class="inputbox">
                <i class="iconfont icon-lock"></i>
                <input type="password" v-model="formData.password" required @input="validateForm('password')"
                  autocomplete="new-password">
                <label :class="{ 'active-label': formData.password }">密码</label>
                <div v-if="errors.password" class="error">密码不能为空</div>
              </div>

              <div class="inputbox" style="opacity: 0;">
                <i class="iconfont icon-lock"></i>
                <input type="password">
                <label>密码</label>
                <div v-if="errors.password" class="error">密码不能为空</div>
              </div>
            </div>

            <div v-if="ismain == false">
              <div class="inputbox">
                <i class="iconfont icon-user"></i>
                <input type="text" v-model="formData.parentMobile" required @input="validateForm('parentMobile')"
                  autocomplete="new-password">
                <label :class="{ 'active-label': formData.parentMobile }">主账号手机号码</label>
                <div v-if="errors.parentMobile" class="error">请输入主账号手机号码</div>
              </div>
              <div class="inputbox">
                <i class="iconfont icon-user"></i>
                <input type="text" v-model="formData.username" required @input="validateForm('username')"
                  autocomplete="new-password">
                <label :class="{ 'active-label': formData.username }">子账号用户名</label>
                <div v-if="errors.username" class="error">用户名不能为空</div>
              </div>
              <div class="inputbox">
                <i class="iconfont icon-lock"></i>
                <input type="password" v-model="formData.password" required @input="validateForm('password')"
                  autocomplete="new-password">
                <label :class="{ 'active-label': formData.password }">密码</label>
                <div v-if="errors.password" class="error">密码不能为空</div>
              </div>
            </div>
            <div class="forget">
              <label><input type="checkbox" v-model="agreeTerms">同意用户协议</label>
              <a href="#">忘记密码</a>
            </div>
            <!-- 添加登录按钮禁用状态 -->
            <button type="submit" :disabled="!agreeTerms || isLoggingIn">
              {{ isLoggingIn ? '登录中...' : '登录' }}
            </button>
          </form>
        </div>
      </div>
    </section>
  </div>
</template>
<script setup>
import { useIndexStore } from "@/store/path";
import router from "@/route/index";
import { ref, reactive, onMounted } from "vue";
import { vToast } from "@/plugins/vToast";
import { post } from "@/request";
const ismain = ref(true);
const indexStore = useIndexStore();
const formData = reactive({
  username: "",
  password: "",
  parentMobile: "", // 新增：主账号手机号码
});
const errors = reactive({
  username: false,
  password: false,
  parentMobile: false, // 新增：主账号手机号码错误状态
});
const agreeTerms = ref(false);
const isLoggingIn = ref(false);

// 表单验证
const validateForm = (name) => {
  errors[name] = !formData[name].trim();
  return !errors[name];
};

// 切换登录类型时重置表单数据
const toggleLoginType = () => {
  ismain.value = !ismain.value;
  
  // 重置所有错误状态
  Object.keys(errors).forEach(key => {
    errors[key] = false;
  });
  
  // 如果从主账号切换到子账号，保留用户名（可能是子账号用户名）
  // 如果从子账号切换到主账号，清空parentMobile
  if (ismain.value) {
    formData.parentMobile = "";
  }
};

const handleLogin = async () => {
    // 根据登录类型进行不同的验证
    if (ismain.value) {
      // 主账号登录验证
      if (!validateForm('username') || !validateForm('password')) {
        vToast({ message: "请填写完整信息", duration: 2000 });
        return;
      }
    } else {
      // 子账号登录验证
      if (!validateForm('parentMobile') || !validateForm('username') || !validateForm('password')) {
        vToast({ message: "请填写完整信息", duration: 2000 });
        return;
      }
      
      // 验证手机号格式
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(formData.parentMobile)) {
        vToast({ message: "请输入正确的手机号格式", duration: 2000 });
        return;
      }
    }

    // 检查是否同意协议
    if (!agreeTerms.value) {
      vToast({ message: "请同意用户协议", duration: 2000 });
      return;
    }

    isLoggingIn.value = true;

    try {
      let response;
      
      // 统一使用/user/login接口进行登录
      if (ismain.value) {
        // 主账号登录
        response = await post('/user/login', {
          username: formData.username,
          password: formData.password,
          captcha_code: "1111" // 模拟验证码
        });
      } else {
        // 子账号登录 - 使用统一的登录接口
        response = await post('/user/login', {
          username: formData.username,
          password: formData.password,
          parent_mobile: formData.parentMobile,
          is_sub_account: true
        });
      }

    if (response.code === 200) {
      await vToast({
        message: "登录成功,跳转中...",
        duration: 1000,
      });

      // 更新全局状态
      indexStore.$patch({
        token: response.data.token,
        userInfo: {
          username: formData.username,
          permission: response.data.user_info?.permission || "member", // 修正为正确的默认权限值
          is_sub_account: !ismain.value, // 标识是否为子账号
          // 保存后端返回的完整用户信息
          ...response.data.user_info
        }
      });

      // 保存到localStorage - 确保is_sub_account和is_sub字段被明确正确保存
      const userInfoToStore = {
        ...response.data.user_info,
        permission: response.data.user_info?.permission || "member",
        is_sub_account: !ismain.value,
        // 明确设置is_sub字段为字符串类型，避免类型转换问题
        is_sub: response.data.user_info?.is_sub !== undefined ? String(response.data.user_info.is_sub) : (ismain.value ? '0' : '1')
      };
      localStorage.setItem("token", response.data.token);
      localStorage.setItem("userInfo", JSON.stringify(userInfoToStore));

      // 路由跳转到dashboard
      setTimeout(() => {
        router.push({ path: "/" }).catch(err => {
          console.error("路由跳转失败:", err);
          vToast({ message: "跳转失败，请重试", duration: 2000 });
        });
      }, 200);
    } else {
      vToast({ message: response.msg || "登录失败", duration: 2000 });
    }
  } catch (error) {
    console.error("登录请求异常:", error);
    vToast({ message: error.message || "登录异常，请稍后重试", duration: 2000 });
  } finally {
    isLoggingIn.value = false;
  }
};
function qiehuan(val) {

  ismain == false

}

onMounted(() => {
  // 初始视频播放设置
  const video = document.querySelector('.bgVideo');
  if (video) {
    video.play().catch(e => console.log("视频自动播放失败:", e));
  }
});
</script>

<style lang="less">
@import url("@/assets/css/style.less");
@import url("@/assets/css/iconfont/iconfont.css");
</style>
<style lang="less" scoped>
.lines {
  border-bottom: solid 1px white;
}

.huiline {
  border-bottom: solid 1px rgb(155, 155, 155);
}

.navs {
  position: absolute;
  right: 20px;
  top: 20px;
  width: 150px;
}

.svg {
  float: right;
  margin-right: 3px;
  display: block;
}

.navs div {
  text-align: center;
  cursor: pointer;
  color: white;
  float: right;
}

.userPage {
  height: 100vh;
  width: 100vw;
  display: flex;

  section {
    display: flex;

    justify-content: center;

    align-items: center;

    min-height: 100vh;

    width: 100%;

    background-position: center;

    background-size: cover;
  }

  .bgVideo {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .form-box {
    position: relative;
    width: 320px;
    padding: 44px;
    background: rgba(13, 18, 26, .6);
    border: none;
    border-radius: 4px;
    backdrop-filter: blur(8px);
    display: flex;
    justify-content: center;
    align-items: center;
  }

  h2 {
    padding: 36px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
  }

  .logo {
    width: 50px;
  }

  .inputbox {
    position: relative;
    margin: 30px 0;
    border-bottom: 1px solid rgba(255, 255, 255, .3);
  }

  .inputbox label {
    position: absolute;
    top: 50%;
    left: 5px;
    transform: translateY(-50%);
    color: rgba(255, 255, 255, .6);
    font-size: 1em;
    pointer-events: none;
    transition: 0.5s;
  }

  /* animations: start */

  input:focus~label,
  input:valid~label {
    top: -5px;
  }

  /* animation:end */

  .inputbox input {
    width: 100%;
    height: 50px;
    background: transparent;
    border: none;
    outline: none;
    font-size: 1em;
    padding: 0 35px 0 5px;
    color: rgba(255, 255, 255, .6);
  }

  .inputbox i {
    position: absolute;
    right: 8px;
    color: rgba(255, 255, 255, .6);
    font-size: 1.2em;
    top: 20px;
  }

  .forget {
    margin: -10px 0 17px;
    font-size: 0.9em;
    color: rgba(255, 255, 255, .6);
    display: flex;
    justify-content: space-between;
  }

  .forget label input {
    margin-right: 3px;
  }

  .forget a {
    color: rgba(255, 255, 255, .6);
    text-decoration: none;
  }

  .forget a:hover {
    text-decoration: underline;
  }

  button {
    width: 100%;
    height: 40px;
    border-radius: 4px;
    border: none;
    outline: none;
    cursor: pointer;
    font-size: 1em;
    font-weight: 600;
    background-color: rgba(255, 255, 255, .1);
    color: var(--bs-bg-color);
  }

  .register {
    font-size: 0.9em;
    color: var(--bs-bg-color);
    text-align: center;
    margin: 25px 0 10px;
  }

  .register p a {
    text-decoration: none;
    color: var(--bs-bg-color);
    font-weight: 600;
  }

  .register p a:hover {
    text-decoration: underline;
  }

  /* Responsiveness:Start */
  @media screen and (max-width: 480px) {
    .form-box {
      width: 100%;
      border-radius: 0px;
    }
  }
}

/* 新增错误提示样式 */
.error {
  color: #ff4757;
  font-size: 0.8rem;
  position: absolute;
  bottom: -20px;
  left: 0;
}

/* 激活状态的标签 */
.active-label {
  top: -5px !important;
  font-size: 0.8em;
}

.userPage {
  position: relative;
  height: 100vh;
  width: 100vw;
  overflow: hidden;

  /* 视频背景层 */
  .bgVideo {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    z-index: 0;
  }

  section {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    width: 100%;
  }

  .inputbox {
    position: relative;
    margin-bottom: 50px;
    /* 给错误提示留空间 */
  }

  button:disabled {
    cursor: not-allowed;
    opacity: .4;
  }
}
</style>